import 'dart:math';

import 'package:flutter/material.dart';
import 'package:kq_flutter_core_widget/extentions/kq_extentions.dart';
import 'package:kq_flutter_core_widget/utils/kq_screen_util.dart';
import 'package:kq_flutter_core_widget/utils/str_util.dart';
import 'package:kq_flutter_core_widget/widgets/button/kq_ink_well.dart';
import 'package:kq_flutter_core_widget/utils/ex/kq_ex.dart';

import '../../config/kq_pad_global.dart';
import '../../resources/images.dart';
import '../../resources/kq_pad_theme_colors.dart';
import '../../theme/kq_theme_manager.dart';
import '../divider/kq_pad_divider.dart';
import 'entity/kq_form_entity.dart';

/// 通用表单组件 - 单选组件
///
/// [ItemType.radio]
///
/// 结合 KqPadFormEntity 使用
///
/// @author 周卓
///
class KqPadRadioItemView extends StatefulWidget {
  /// 通用属性
  final KqPadFormEntity entity;

  /// 单选组件单选点击回调
  final Function(KqPadFormEntity entity, RadioData radioData)? onRadioChanged;

  const KqPadRadioItemView(
      {Key? key, required this.entity, this.onRadioChanged})
      : super(key: key);

  @override
  KqPadRadioItemViewState createState() => KqPadRadioItemViewState();
}

class KqPadRadioItemViewState extends State<KqPadRadioItemView> {
  @override
  void initState() {
    widget.entity.widgetState = this;
    super.initState();
  }

  /// 主动刷新方法
  update() {
    if (mounted) {
      setState(() {});
    }
  }

  /// 定位到该条数据，滚动到屏幕中央
  location(ScrollController? scrollController) {
    if (scrollController == null) {
      return;
    }
    //拿到控件的位置
    var position = context.position();
    var dy = position?.dy;
    if (scrollController.hasClients && dy != null) {
      var util = KqScreenUtil();
      var screenHeight = util.screenHeight;
      var targetY = scrollController.offset + dy - screenHeight / 2;
      var maxY = scrollController.position.maxScrollExtent;
      scrollController.jumpTo(max(0, min(targetY, maxY)));
    }
  }

  @override
  Widget build(BuildContext context) {
    // 如果外层实体是反复重新创建的，则需要在此重新赋值
    widget.entity.widgetState = this;
    var bgColor = widget.entity.backgroundColor ?? KqPadThemeColors.bgWhite;
    return Visibility(
      visible: widget.entity.visible,
      child: Column(
        children: [
          Container(
            color: bgColor,
            child: Row(
              children: <Widget>[
                KqPadVerticalDivider(
                  height: 18.r,
                  color: KqPadThemeColors.bgF0,
                ),

                // 标题
                Container(
                  color: KqPadThemeColors.bgFA,
                  height: 18.r,
                  width: 60.r,
                  padding: EdgeInsets.symmetric(horizontal: 6.r),
                  alignment: Alignment.centerRight,
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.end,
                    children: [
                      /// 左边自定义控件
                      /// 自定义布局，来自实体类
                      widget.entity.customLeftView != null
                          ? widget.entity.customLeftView!(widget.entity)
                          : Container(),

                      LimitedBox(
                        maxWidth: 48.r,
                        child: Text(
                          widget.entity.title,
                          maxLines: 2,
                          overflow: TextOverflow.ellipsis,
                          textAlign: TextAlign.end,
                          style: widget.entity.titleStyle ??
                              TextStyle(
                                  fontSize: KqPadThemeManager.instance
                                          .getConfig()
                                          .formConfig
                                          .titleFontSize ??
                                      6.sp,
                                  color: widget.entity.titleColor ??
                                      KqPadThemeColors.text26),
                        ),
                      ),
                    ],
                  ),
                ),

                KqPadVerticalDivider(
                  height: 18.r,
                  color: KqPadThemeColors.bgF0,
                ),

                SizedBox(
                  width: 2.r,
                ),

                /// 右侧按钮组
                Expanded(
                  child: LayoutBuilder(
                    builder: (context, constraints) {
                      double maxWidth = constraints.maxWidth;
                      return Row(
                        mainAxisAlignment: MainAxisAlignment.start,
                        children: _renderRadioButtonList(maxWidth),
                      );
                    },
                  ),
                ),

                KqPadVerticalDivider(
                  height: 18.r,
                  color: KqPadThemeColors.bgF0,
                ),
              ],
            ),
          ),

          /// 分割线
          Visibility(
              visible: !widget.entity.hideDivider,
              child: const KqPadDivider(
                color: KqPadThemeColors.bgF0,
              ))
        ],
      ),
    );
  }

  List<Widget> _renderRadioButtonList(double maxWidth) {
    double maxItemWidth = maxWidth / widget.entity.radioData!.length;
    if (!widget.entity.isEditable()) {
      //非编辑模式，只显示选中按钮的文字
      for (var data in widget.entity.radioData!) {
        if (data.itemId == widget.entity.valueForSubmit) {
          return [
            Container(
              margin: EdgeInsets.only(right: 8.r),
              child: LimitedBox(
                maxWidth: maxItemWidth - 8.r,
                child: Text(
                  data.item,
                  maxLines: 2,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(
                      fontSize: KqPadThemeManager.instance
                              .getConfig()
                              .formConfig
                              .contentFontSize ??
                          6.sp,
                      color: KqPadThemeColors.text26),
                ),
              ),
            )
          ];
        }
      }
      return [];
    }
    String allText = StrUtil.concatDynamic(
            widget.entity.radioData, (t) => t.item,
            split: '') ??
        '';
    TextStyle textStyle = TextStyle(
        fontSize:
            KqPadThemeManager.instance.getConfig().formConfig.contentFontSize ??
                6.sp,
        color: widget.entity.contentColor ?? KqPadThemeColors.text26);
    double totalWidth =
        allText.isEmpty ? 0 : measureTextWidth(allText, textStyle: textStyle);
    return widget.entity.radioData
            ?.map(
              (e) => _renderRadioButtonItem(
                  e,
                  maxItemWidth,
                  totalWidth,
                  widget.entity.radioData!.length,
                  textStyle,
                  widget.entity.radioData!.indexOf(e)),
            )
            .toList() ??
        [];
  }

  /// 画笔，用于测量
  TextPainter painter = TextPainter(textDirection: TextDirection.ltr);

  /// 获取文本宽度
  double measureTextWidth(String text, {TextStyle? textStyle}) {
    painter.text = TextSpan(
      text: text,
      style: textStyle,
    );

    painter.layout();
    return painter.width;
  }

  Widget _renderRadioButtonItem(RadioData data, double maxItemWidth,
      double totalTextWidth, int itemCount, TextStyle textStyle, int index) {
    double maxTextItemWidth = maxItemWidth - 2.r - 7.r - 2.r - 8.r - 1.r;
    bool needMax = totalTextWidth > maxTextItemWidth * itemCount;
    Widget child = Text(
      data.item,
      maxLines: 2,
      overflow: TextOverflow.ellipsis,
      style: textStyle,
    );
    if (needMax) {
      child = LimitedBox(
        maxWidth: maxTextItemWidth,
        child: child,
      );
    }
    return Container(
      margin: EdgeInsets.only(right: index == itemCount - 1 ? 0 : 2.r),
      child: KqInkWell(
        radius: 2.r,
        enableRipple: false,
        onTap: () {
          setState(() {
            if (widget.entity.canInvert == true) {
              if (widget.entity.valueForSubmit == data.itemId) {
                widget.entity.valueForSubmit = null;
                widget.entity.valueForShow = null;
              } else {
                widget.entity.valueForSubmit = data.itemId;
                widget.entity.valueForShow = data.item;
              }
            } else {
              widget.entity.valueForSubmit = data.itemId;
              widget.entity.valueForShow = data.item;
            }

            //回调
            widget.entity.onRadioChanged?.call(widget.entity, data);
            widget.onRadioChanged?.call(widget.entity, data);
          });
        },
        borderWidth: 0,
        child: Padding(
          padding: EdgeInsets.symmetric(horizontal: 4.r),
          child: Row(
            mainAxisSize: MainAxisSize.min,
            children: [
              Image.asset(
                getImgPath(data, data.itemId == widget.entity.valueForSubmit),
                width: 7.r,
                height: 7.r,
                fit: BoxFit.fill,
                color: data.itemId == widget.entity.valueForSubmit
                    ? KqPadThemeManager.getCommonConfig().mainLightColor
                    : null,
                package: getPackageName(
                    data, data.itemId == widget.entity.valueForSubmit),
              ),
              Container(
                margin: EdgeInsets.only(left: 2.r),
                alignment: AlignmentDirectional.centerStart,
                child: child,
              )
            ],
          ),
        ),
      ),
    );
  }

  String? getPackageName(RadioData data, bool chosen) {
    return chosen
        ? (data.checkedImgPath != null ? null : KqPadGlobal.packageName)
        : (data.unCheckedImgPath != null ? null : KqPadGlobal.packageName);
  }

  /// 获取图片
  String getImgPath(RadioData data, bool chosen) {
    return chosen
        ? (data.checkedImgPath ?? Images.commonIcRadio16SelectedEnabled)
        : (data.unCheckedImgPath ?? Images.commonIcRadio16UnselectedEnabled);
  }
}

/// 单选数据
class RadioData {
  /// 显示名字
  String item;

  /// 选择后用户提交id
  String itemId;

  /// 选中的图片
  String? checkedImgPath;

  /// 未选中的图片
  String? unCheckedImgPath;

  /// 图片的包名，如果是组件库里的图片，要用[KqPadGlobal.packageName]
  String? package;

  RadioData({
    required this.item,
    required this.itemId,
    this.checkedImgPath,
    this.unCheckedImgPath,
    this.package,
  });
}
